package com.huahan.auth.exception;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.huahan.auth.security.component.BusinessAuthenticationException;

import java.io.IOException;
import java.util.Map;

public class AuthenticationExceptionSerializer
        extends StdSerializer<BusinessAuthenticationException> {
    protected AuthenticationExceptionSerializer() {
        super(BusinessAuthenticationException.class);
    }

    @Override
    public void serialize(BusinessAuthenticationException e, JsonGenerator jsonGenerator,
                          SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeNumberField("code", e.getCode());
        jsonGenerator.writeStringField("message", e.getMessage());
        if (e.getAdditionalInformation() != null) {
            for (Map.Entry<String, String> entry : e.getAdditionalInformation().entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                jsonGenerator.writeStringField(key, value);
            }
        }
        jsonGenerator.writeEndObject();
    }
}
